<?php

namespace app\model;


use think\Model;
use think\facade\Cache;
use think\facade\Db;

class EcSkuModel extends Model
{


    /**
     * 该表将与模型关联。
     * @var string
     */
    protected $table = 'ec_sku';

    // 开启自动时间戳（默认为整型int）
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     * 返回 状态数据 访问器的值
     * @return string
     */
    public function getStatusDataAttr(): array
    {
        $data = [
            ['text' => '正常', 'value' => 1],
            ['text' => '禁用', 'value' => 0],
        ];
        return $data;
    }

    /**
     * 返回 状态 访问器的值
     * @return string
     */
    public function getStatusTextAttr()
    {
        $value = $this->getData('status');
        if (is_numeric($value)) {
            $value = intval($value);
        }
        $data = (array) $this->getStatusDataAttr();
        $result = array_filter($data, function ($v) use ($value) {
            return $v['value'] == $value;
        }, ARRAY_FILTER_USE_BOTH);
        return $result ? current($result)['text'] : $value;
    }

    public static function addRecords($goodsId, $data)
    {
        self::where('goods_id', $goodsId)->delete();
        $list = [];
        foreach ($data as $row) {
            $row['goods_id'] = $goodsId;
            $row['created_at'] = time();
            $list[] = $row;
        }
        ModelUtils::cacheRefresh('ec_sku');
        return Db::table((new static())->table)->insertAll($list);
    }

    public static function getSkuNoData($goodsId)
    {
        $cacheKey = "ec_sku_nos_{$goodsId}";
        $data = Cache::get($cacheKey);
        if ($data) {
            return $data;
        }
        $data = Db::table((new static())->table)->where('goods_id', $goodsId)->field('sku_no as `value`, expire_date as `text`')->select();
        Cache::set($cacheKey, $data, 20);
        return $data;
    }

    /**
     * 获取SKU列表
     */
    public static function getSkuList($goodsId, $skuNoArr = [])
    {
        // 不能有缓存
        $data = Db::table((new static())->table)->where('goods_id', $goodsId)->where(function ($query) use ($skuNoArr) {
            if ($skuNoArr) {
                $isFirst = true;
                foreach ($skuNoArr as $skuNo) {
                    if ($isFirst) {
                        $query->where('sku_no', 'like', "%{$skuNo}%");
                    } else {
                        $query->orWhere('sku_no', 'like', "%{$skuNo}%");
                    }
                    $isFirst = false;
                }
            }
        })->field(['sku_no', 'price', 'quantity', 'icon', 'is_default'])->select();
        return $data;
    }

    /**
     * 获取SKU数量（用于判断是否缺货）
     */
    public static function getSkuQuantity($goodsId, $skuNoArr = [])
    {
        // 不能有缓存
        $data = Db::table((new static())->table)->where('goods_id', $goodsId)->where(function ($query) use ($skuNoArr) {
            if ($skuNoArr) {
                $isFirst = true;
                foreach ($skuNoArr as $skuNo) {
                    if ($isFirst) {
                        $query->where('sku_no', 'like', "%{$skuNo}%");
                    } else {
                        $query->orWhere('sku_no', 'like', "%{$skuNo}%");
                    }
                    $isFirst = false;
                }
            }
        })->sum('quantity');
        return $data;
    }
}
